#!/usr/bin/env python3
###
# @Author: Logan.Li
# @Gitee: https://gitee.com/attacker
# @email: admin@attacker.club
# @Date: 2025-03-14 08:40:30
# @LastEditTime: 2025-03-14 08:40:35
# @Description: 阿里云ECS监控模块
###

import os
import json
import logging
from typing import Dict, List
from aliyunsdkecs.request.v20140526 import DescribeInstancesRequest
from ..core import AliyunMonitorBase

class ECSMonitor(AliyunMonitorBase):
    """ECS实例监控"""
    
    def __init__(self, config: Dict):
        super().__init__(config)
        self.namespace = "acs_ecs_dashboard"
        
    def list_instances(self) -> List[Dict]:
        """获取ECS实例列表"""
        try:
            request = DescribeInstancesRequest.DescribeInstancesRequest()
            response = self.client.do_action_with_exception(request)
            instances = json.loads(response).get('Instances', {}).get('Instance', [])
            return instances
        except Exception as e:
            logging.error(f"获取ECS实例列表失败: {e}")
            return []
            
    def setup_instance_monitoring(self, instance_id: str, instance_name: str):
        """设置实例监控
        
        Args:
            instance_id: 实例ID
            instance_name: 实例名称
        """
        dimensions = [{"instanceId": instance_id}]
        
        # CPU使用率告警
        self.create_alarm_rule(
            rule_name=f"{instance_name}-CPU使用率告警",
            namespace=self.namespace,
            metric_name="CPUUtilization",
            dimensions=dimensions,
            threshold=float(self.config['thresholds']['cpu']),
            contact_groups=self.config['contact_groups'],
            period=300
        )
        
        # 内存使用率告警
        self.create_alarm_rule(
            rule_name=f"{instance_name}-内存使用率告警",
            namespace=self.namespace,
            metric_name="memory_usedutilization",
            dimensions=dimensions,
            threshold=float(self.config['thresholds']['memory']),
            contact_groups=self.config['contact_groups'],
            period=300
        )
        
        # 磁盘使用率告警
        self.create_alarm_rule(
            rule_name=f"{instance_name}-磁盘使用率告警",
            namespace=self.namespace,
            metric_name="diskusage_utilization",
            dimensions=dimensions,
            threshold=float(self.config['thresholds']['disk']),
            contact_groups=self.config['contact_groups'],
            period=300
        )
        
    def monitor_all_instances(self):
        """监控所有ECS实例"""
        instances = self.list_instances()
        for instance in instances:
            instance_id = instance['InstanceId']
            instance_name = instance.get('InstanceName', instance_id)
            self.setup_instance_monitoring(instance_id, instance_name)
            logging.info(f"已设置实例监控: {instance_name}")
            
    def get_instance_metrics(self, instance_id: str) -> Dict:
        """获取实例的监控指标
        
        Args:
            instance_id: 实例ID
        """
        dimensions = [{"instanceId": instance_id}]
        metrics = {}
        
        # CPU使用率
        cpu_data = self.get_metric_data(
            namespace=self.namespace,
            metric_name="CPUUtilization",
            dimensions=dimensions
        )
        metrics['cpu'] = cpu_data
        
        # 内存使用率
        memory_data = self.get_metric_data(
            namespace=self.namespace,
            metric_name="memory_usedutilization",
            dimensions=dimensions
        )
        metrics['memory'] = memory_data
        
        # 磁盘使用率
        disk_data = self.get_metric_data(
            namespace=self.namespace,
            metric_name="diskusage_utilization",
            dimensions=dimensions
        )
        metrics['disk'] = disk_data
        
        return metrics

# 使用示例
if __name__ == "__main__":
    # 配置示例
    config = {
        "access_key": "your_access_key",
        "secret_key": "your_secret_key",
        "region": "cn-hangzhou",
        "thresholds": {
            "cpu": 80,
            "memory": 85,
            "disk": 90
        },
        "contact_groups": ["default"],
        "notification": {
            "dingtalk": {
                "enabled": True,
                "webhook": "your_webhook_url",
                "secret": "your_secret"
            },
            "lark": {
                "enabled": True,
                "webhook": "your_webhook_url"
            }
        }
    }
    
    monitor = ECSMonitor(config)
    
    # 监控所有实例
    monitor.monitor_all_instances()
    
    # 获取特定实例的指标
    metrics = monitor.get_instance_metrics("your_instance_id")
    print(json.dumps(metrics, indent=2))
